package net.chamerling.blog.axis2reroute.client;

import java.io.File;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.OperationClient;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.wsdl.WSDLConstants;

public class App {
	public static void main(String[] args) throws Exception {
		App app = new App();
		SOAPEnvelope envelope = app.invoke();
		System.out.println("RESULT = " + envelope);
	}

	public SOAPEnvelope invoke() {
		SOAPEnvelope responseEnvelope = null;
		EndpointReference targetEPR = new EndpointReference(
				"http://localhost:7600/petals/ws/InformationService");

		try {

			File f = new File(".", "src/main/axis2");

			String axis2ConfPath = f.getAbsolutePath();
			ConfigurationContext ctx = ConfigurationContextFactory
					.createConfigurationContextFromFileSystem(axis2ConfPath,
							null);

			ServiceClient client = new ServiceClient(ctx, null);

			Options options = new Options();

			options.setTo(targetEPR);
			options.setAction("getVersion");
			client.setOptions(options);

			MessageContext msgContext = new MessageContext();
			SOAPEnvelope envelope = this.createSoapEnvelope();
			msgContext.setEnvelope(envelope);

			OperationClient opClient = client
					.createClient(ServiceClient.ANON_OUT_IN_OP);
			opClient.addMessageContext(msgContext);
			opClient.execute(true);

			MessageContext responseMsgCtx = opClient
					.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
			responseEnvelope = responseMsgCtx.getEnvelope();

		} catch (Exception e) {
			System.err.println(" ERROR : " + e.getMessage());
		}
		return responseEnvelope;
	}

	/**
	 * @param sayHelloStr
	 * @return
	 */
	private SOAPEnvelope createSoapEnvelope() {
		SOAPEnvelope envelope = OMAbstractFactory.getSOAP11Factory()
				.getDefaultEnvelope();
		envelope.getBody().addChild(this.getOMElement());
		return envelope;
	}

	private OMElement getOMElement() {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = fac.createOMNamespace(
				"http://api.ws.kernel.petals.ow2.org/", "api");
		OMElement method = fac.createOMElement("getVersion", omNs);
		return method;
	}
}
